package com.ervanalb.cellradio.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import com.ervanalb.cellradio.shared.communicator.PacketSource;
import com.ervanalb.cellradio.shared.communicator.packets.Packet;

/**
 * Implements a PacketSource which reads packets from a DatagramSocket. Calling
 * receive() blocks until data comes in on the socket, parses it as a packet,
 * and returns it.
 * 
 * @author eric
 */
public class SocketSource implements PacketSource {

	public DatagramSocket sock;
	protected DatagramPacket p;
	protected byte[] buffer;

	public static final int DGRAM_BUF_SIZE = 1024;

	public SocketSource(int port) throws SocketException {
		sock = new DatagramSocket(port);
		buffer = new byte[DGRAM_BUF_SIZE];
	}

	@Override
	public Packet receive(long timeout) throws IOException {
		Packet parsed;
		p = new DatagramPacket(buffer, DGRAM_BUF_SIZE);
		long timeDone = System.currentTimeMillis() + timeout;
		long now;
		for (;;) {
			now = System.currentTimeMillis();
			if (now >= timeDone) {
				parsed = null;
				break;
			}
			sock.setSoTimeout((int) (timeDone - now));
			try {
				sock.receive(p);
				parsed = new Packet(p);
				break;
			} catch (SocketTimeoutException e) {
			}
		}

		return parsed;
	}
}
